<template>
  <view class="message-page">
 

    <!-- 搜索栏 -->
   

    <!-- 会话列表 -->
    <view class="conversation-list">
      <view 
        v-for="conversation in conversationList" 
        :key="conversation.id"
        class="conversation-item"
        @click="openChat(conversation)"
      >
        <view class="avatar-section">
          <u-avatar 
            :src="getConversationAvatar(conversation)" 
            size="50"
          ></u-avatar>
          <u-badge 
            v-if="conversation.unreadCount > 0"
            :value="conversation.unreadCount > 99 ? '99+' : conversation.unreadCount"
            :offset="[-5, 5]"
          ></u-badge>
        </view>
        
        <view class="content-section">
          <view class="header">
            <text class="name">{{ getConversationName(conversation) }}</text>
            <text class="time">{{ formatTime(conversation.lastMessageTime) }}</text>
          </view>
          <view class="message">
            <text class="content">{{ conversation.lastMessageContent || '暂无消息' }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <u-empty 
      v-if="!loading && conversationList.length === 0"
      text="暂无会话"
      icon="/static/icons/empty-message.png"
    ></u-empty>

    <!-- 加载中 -->
    <u-loading-page :loading="loading"></u-loading-page>

    <!-- 添加菜单 -->
    <u-action-sheet 
      v-model="showAddMenu" 
      :actions="addActions"
      @select="handleAddAction"
    ></u-action-sheet>

    <!-- 新建会话弹窗 -->
    <u-modal 
      v-model="showNewChatModal" 
      title="新建会话"
      :show-cancel-button="true"
      @confirm="createNewChat"
    >
      <view class="new-chat-form">
        <u-form-item label="用户ID">
          <u-input v-model="newChatForm.targetUserId" placeholder="请输入用户ID"></u-input>
        </u-form-item>
      </view>
    </u-modal>
  </view>
</template>

<script>
import { getConversationList, createPrivateConversation } from '@/api/message'
import { formatTime } from '@/utils/date'

export default {
  name: 'MessageIndex',
  data() {
    return {
      loading: false,
      searchKeyword: '',
      conversationList: [],
      showAddMenu: false,
      showNewChatModal: false,
      newChatForm: {
        targetUserId: ''
      },
      addActions: [
        { name: '新建私聊', value: 'private' },
        { name: '新建群聊', value: 'group' }
      ]
    }
  },
  
  onLoad() {
    this.loadConversations()
  },
  
  onShow() {
    // 页面显示时刷新会话列表
    this.loadConversations()
  },
  
  onPullDownRefresh() {
    this.loadConversations().finally(() => {
      uni.stopPullDownRefresh()
    })
  },
  
  methods: {
    // 加载会话列表
    async loadConversations() {
      try {
        this.loading = true
        const res = await getConversationList()
        if (res.code === 200) {
			console.log(11111111111111111 )
			console.log(res.data )
          this.conversationList = res.data || []
        }
      } catch (error) {
        console.error('加载会话列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'error'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 搜索会话
    handleSearch() {
      // TODO: 实现搜索功能
      console.log('搜索:', this.searchKeyword)
    },
    
    // 打开聊天页面
    openChat(conversation) {
      uni.navigateTo({
        url: `/pages/message/chat?conversationId=${conversation.id}&name=${encodeURIComponent(this.getConversationName(conversation))}`
      })
    },
    
    // 获取会话名称
    getConversationName(conversation) {
      if (conversation.type === 'GROUP') {
        return conversation.name || '群聊'
      } else {
        // 私聊显示对方用户名
        return this.getOtherUserName(conversation) || '私聊'
      }
    },
    
    // 获取会话头像
    getConversationAvatar(conversation) {
      if (conversation.type === 'GROUP') {
        return conversation.avatar || '/static/icons/group-avatar.png'
      } else {
        // 私聊显示对方用户头像
        return this.getOtherUserAvatar(conversation) || '/static/icons/default-avatar.png'
      }
    },
    
    // 获取对方用户名
    getOtherUserName(conversation) {
      try {
        const userInfo = uni.getStorageSync('userInfo')
        const currentUserId = userInfo.id
        const participants = JSON.parse(conversation.participants || '[]')
        
        // 找到对方用户ID
        const otherUserId = participants.find(id => id !== currentUserId)
        
        // TODO: 这里应该从用户信息中获取真实姓名
        // 暂时返回用户ID
        return conversation.otherUserName
      } catch (error) {
        console.error('解析参与者信息失败:', error)
        return '私聊'
      }
    },
    
    // 获取对方用户头像
    getOtherUserAvatar(conversation) {
      // TODO: 这里应该从用户信息中获取真实头像
      return conversation.otherUserAvatar
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      return formatTime(time)
    },
    
    // 处理添加操作
    handleAddAction(action) {
      if (action.value === 'private') {
        this.showNewChatModal = true
      } else if (action.value === 'group') {
        uni.navigateTo({
          url: '/pages/message/create-group'
        })
      }
    },
    
    // 创建新聊天
    async createNewChat() {
      if (!this.newChatForm.targetUserId) {
        uni.showToast({
          title: '请输入用户ID',
          icon: 'error'
        })
        return
      }
      
      try {
        const res = await createPrivateConversation(this.newChatForm.targetUserId)
        if (res.code === 200) {
          uni.showToast({
            title: '创建成功',
            icon: 'success'
          })
          this.showNewChatModal = false
          this.newChatForm.targetUserId = ''
          this.loadConversations()
        }
      } catch (error) {
        console.error('创建会话失败:', error)
        uni.showToast({
          title: '创建失败',
          icon: 'error'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.message-page {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.search-section {
  padding: 20rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  flex-shrink: 0; /* 不缩放 */
}

.conversation-list {
  // background-color: #000000;
  flex: 1;
  overflow-y: auto;
}

.conversation-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1px solid #f0f0f0;
  
  &:active {
    background-color: #f5f5f5;
  }
  
  .avatar-section {
    position: relative;
    margin-right: 20rpx;
  }
  
  .content-section {
    flex: 1;
    min-width: 0;
    
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10rpx;
      
      .name {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
      }
      
      .time {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .message {
      .content {
        font-size: 28rpx;
        color: #666;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}

.new-chat-form {
  padding: 40rpx 20rpx;
}
</style>
